const http = require("http");
const fs = require("fs");
const { getMine, getFileMine } = require("./utils/ext");
const path = require("path");
const url = require("url");
http
  .createServer(function (req, res) {
    // http://127.0.0.1:3000/index.html
    // http://127.0.0.1:3000/login.html
    //1.获取地址  req.url
    let pathname = url.parse(req.url).pathname;
    pathname = pathname == "/" ? "/index.html" : pathname;
    let extname = path.extname(pathname);
    //2.通过fs模块读取文件
    if (pathname !== "/favicon.ico") {
      fs.readFile(`./static/itschool` + pathname, (err, data) => {
        if (err) {
          console.log("404");
          res.writeHead(404, { "Content-Type": "text/html;charset=utf-8" });
          res.end("这个页面不存在");
          return;
        }
        let mime = getFileMine(extname);
        res.writeHead(200, { "Content-Type": `${mime};charset=utf-8` });
        res.end(data);
      });
      // fs.readFile(`./static/itschool` + pathname, async (err, data) => {
      //   if (err) {
      //     console.log("404");
      //     res.writeHead(404, { "Content-Type": "text/html;charset=utf-8" });
      //     res.end("这个页面不存在");
      //     return;
      //   }
      //   let mime = await getFileMine(extname);
      //   res.writeHead(200, { "Content-Type": `${mime};charset=utf-8` });
      //   res.end(data);
      // });
    }
  })
  .listen(3000, "localhost", function () {
    console.log("Server running at http://127.0.0.1:3000/");
  });
